import { useEffect, useRef } from 'react';
import { useDrop } from 'react-dnd';
import { v4 as uuidv4 } from 'uuid';
import { FlowNode, FunctionDefinition, NodeStatus } from '../../common/types';
import { useFlowStore } from '../../stores/flowStore';
import { FunctionNode } from './FunctionNode'; // 下一节实现
import { ConnectionRenderer } from './ConnectionRenderer'; // 下一节实现

export const FlowCanvas = () => {
  const nodes = useFlowStore((state) => state.nodes);
  const addNode = useFlowStore((state) => state.addNode);
  const setSelectedNode = useFlowStore((state) => state.setSelectedNode);
  const containerRef = useRef<HTMLDivElement>(null);

  const [, drop] = useDrop(() => ({
    accept: 'FUNCTION',
    drop: (item: { func: FunctionDefinition }, monitor) => {
      const offset = monitor.getClientOffset();
      const containerRect = containerRef.current?.getBoundingClientRect();

      if (offset&&containerRect) {
        const x = offset.x - containerRect.left - 100;
        const y = offset.y - containerRect.top - 30;
        const newNode: FlowNode = {
          id: uuidv4(),
          functionId: item.func.id,
          position: { x, y}, // 简单坐标转换
          parameters: Object.fromEntries(
            item.func.parameters.map((p) => [p.name, p.defaultValue])
          ),
          status: 'idle',
        };
        addNode(newNode);
      }
    },
  }));

  return (
    <div 
      ref={(el) => {
        drop(el);
        containerRef.current = el;
      }}
      className="flow-canvas"
      onClick={(e) => {
        if (e.target === e.currentTarget) setSelectedNode(null);
      }}
    >
      <ConnectionRenderer />
      {nodes.map((node) => (
        <FunctionNode key={node.id} node={node} />
      ))}
    </div>
  );
};